package com.yan.processer;

import cn.hutool.core.lang.ClassScaner;
import cn.hutool.core.map.MapUtil;
import com.yan.anno.HandlerType;
import com.yan.handler.AbstractHandler;
import com.yan.handler.HandlerContext;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class HandlerProcessor implements BeanFactoryPostProcessor, ApplicationContextAware {
    private ApplicationContext applicationContext;

    @Override
    @SuppressWarnings("unchecked")
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        Map<String, AbstractHandler> map = MapUtil.newHashMap(3);
        ClassScaner.scanPackageByAnnotation(AbstractHandler.class.getPackage().getName(),
                HandlerType.class)
                .forEach(clazz -> {
                    String value = clazz.getAnnotation(HandlerType.class).value();
                    AbstractHandler abstractHandler = applicationContext.getBean((Class<? extends AbstractHandler>) clazz);
                    map.put(value, abstractHandler);
                });
        HandlerContext bean = applicationContext.getBean(HandlerContext.class);
        bean.setMap(map);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
